package com.song.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.song.entity.Borrower;
import com.song.entity.BorrowerAttach;
import com.song.entity.UserInfo;
import com.song.entity.UserIntegral;
import com.song.entity.vo.BorrowerApprovalVO;
import com.song.entity.vo.BorrowerAttachVO;
import com.song.entity.vo.BorrowerDetailVO;
import com.song.entity.vo.BorrowerVO;
import com.song.enums.BorrowStatusEnum;
import com.song.enums.IntegralEnum;
import com.song.mapper.BorrowerAttachMapper;
import com.song.mapper.BorrowerMapper;
import com.song.mapper.UserInfoMapper;
import com.song.mapper.UserIntegralMapper;
import com.song.service.BorrowerAttachService;
import com.song.service.BorrowerService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.song.service.DictService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 * 借款人 服务实现类
 * </p>
 *
 * @author Song
 * @since 2025-01-03
 */
@Service
public class BorrowerServiceImpl extends ServiceImpl<BorrowerMapper, Borrower> implements BorrowerService {

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private BorrowerAttachMapper borrowerAttachMapper;

    @Autowired
    private BorrowerAttachService borrowerAttachService;

    @Autowired
    private DictService dictService;

    @Autowired
    private UserIntegralMapper userIntegralMapper;


    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveBorrowerVo(BorrowerVO borrowerVO, Long userId) {
         //用户信息有了
        UserInfo userInfo = userInfoMapper.selectById(userId);

        //创建对象
        Borrower borrower = new Borrower();
        //拷贝
        BeanUtils.copyProperties(borrowerVO,borrower);
        //设置其他的属性
        borrower.setUserId(userId);
        borrower.setName(userInfo.getName());
        borrower.setIdCard(userInfo.getIdCard());
        borrower.setMobile(userInfo.getMobile());
        borrower.setStatus(BorrowStatusEnum.BORROW_ING.getStatus());//认证中
        baseMapper.insert(borrower);

        //保存附件
        List<BorrowerAttach> borrowerAttachList = borrowerVO.getBorrowerAttachList();
        borrowerAttachList.forEach(borrowerAttach -> {
            borrowerAttach.setBorrowerId(borrower.getId());
            borrowerAttachMapper.insert(borrowerAttach);

        });

        //更新会员状态
        userInfo.setBorrowAuthStatus(BorrowStatusEnum.BORROW_ING.getStatus());//认证中
        userInfoMapper.updateById(userInfo);



    }

    @Override
    public Integer getBorrowerStatusByUserId(Long userId) {
           // 9527
        QueryWrapper<Borrower> wrapper = new QueryWrapper<>();
        wrapper.select("status").eq("user_id",userId);
        List<Object> objects = baseMapper.selectObjs(wrapper);
        //
        if(objects.size()==0){
             //借款人木有进行信息提交
            return BorrowStatusEnum.NO_BORROW.getStatus();
        }

        Integer status= (Integer) objects.get(0);

        return status;
    }

    @Override
    public IPage<Borrower> listPage(Page<Borrower> pageParam, String keyword) {
        //条件构造器
        QueryWrapper<Borrower> wrapper = new QueryWrapper<>();

        //用户不输入 keyword的场景
        if(StringUtils.isEmpty(keyword)){
              return  baseMapper.selectPage(pageParam,null);
        }

        //输入了 关键字
        wrapper.like("name",keyword).
                or().like("mobile",keyword).
                or().like("id_card",keyword).
                orderByDesc("id");




        return baseMapper.selectPage(pageParam,wrapper);
    }

    @Override
    public BorrowerDetailVO getBorrowerDetailVOById(Long id) {
        //获取借款人信息
        Borrower borrower = baseMapper.selectById(id);
        //填充基本信息
        BorrowerDetailVO borrowerDetailVO = new BorrowerDetailVO();
        //拷贝
        BeanUtils.copyProperties(borrower,borrowerDetailVO);
        //婚否
          borrowerDetailVO.setMarry(borrower.getMarry()?"是":"否");
        // 性别
        borrowerDetailVO.setSex(borrower.getSex()==1?"男":"女");
        //下拉框数据
       String education= dictService.getNameByParentDictCodeAndValue("education",borrower.getEducation());
       String industry= dictService.getNameByParentDictCodeAndValue("industry",borrower.getIndustry());
       String returnSource= dictService.getNameByParentDictCodeAndValue("returnSource",borrower.getReturnSource());
       String relation= dictService.getNameByParentDictCodeAndValue("relation",borrower.getContactsRelation());

       //进行数据的设置
        borrowerDetailVO.setEducation(education);
        borrowerDetailVO.setIndustry(industry);
        borrowerDetailVO.setReturnSource(returnSource);
        borrowerDetailVO.setContactsRelation(relation);

        //审批状态
        String msgStatus = BorrowStatusEnum.getMsgStatus(borrower.getStatus());
        borrowerDetailVO.setStatus(msgStatus);

        //获取附件
       List<BorrowerAttachVO> borrowerAttachVOList = borrowerAttachService.selectBorrowerAttachVoList(id);
        borrowerDetailVO.setBorrowerAttachVOList(borrowerAttachVOList);



        return borrowerDetailVO;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void approval(BorrowerApprovalVO borrowerApprovalVO) {
        //获取借款人的认证状态
        Integer borrowerId = borrowerApprovalVO.getBorrowerId();
        //我要通过  borrowerId 查询 borrower对象
        Borrower borrower = baseMapper.selectById(borrowerId);
        borrower.setStatus(borrowerApprovalVO.getStatus());//拿到状态
        baseMapper.updateById(borrower);//更新操作

        Long userId = borrower.getUserId();
        //查询用户信息
        UserInfo userInfo = userInfoMapper.selectById(userId);

        //处理积分
        UserIntegral userIntegral = new UserIntegral();
        userIntegral.setUserId(userId);//积分的所有者
        userIntegral.setIntegral(borrowerApprovalVO.getInfoIntegral());
        userIntegral.setContent("借款人基础信息");//获取积分说明
        //添加用户积分记录
        userIntegralMapper.insert(userIntegral);

        //加分
       int currentIntegral= userInfo.getIntegral()+borrowerApprovalVO.getInfoIntegral();

       if(borrowerApprovalVO.getIsCarOk()){//判断车辆合法性
           currentIntegral+= IntegralEnum.BORROWER_CAR.getIntegral();
           userIntegral = new UserIntegral();
           userIntegral.setUserId(userId);//积分的所有者
           userIntegral.setIntegral(IntegralEnum.BORROWER_CAR.getIntegral());
           userIntegral.setContent(IntegralEnum.BORROWER_CAR.getMsg());//获取积分说明
           userIntegralMapper.insert(userIntegral);

       }

        if(borrowerApprovalVO.getIdCardOk()){//判断车辆合法性
            currentIntegral+= IntegralEnum.BORROWER_IDCARD.getIntegral();
            userIntegral = new UserIntegral();
            userIntegral.setUserId(userId);//积分的所有者
            userIntegral.setIntegral(IntegralEnum.BORROWER_IDCARD.getIntegral());
            userIntegral.setContent(IntegralEnum.BORROWER_IDCARD.getMsg());//获取积分说明
            userIntegralMapper.insert(userIntegral);

        }

        if(borrowerApprovalVO.getHouseOk()){//判断车辆合法性
            currentIntegral+= IntegralEnum.BORROWER_HOUSE.getIntegral();
            userIntegral = new UserIntegral();
            userIntegral.setUserId(userId);//积分的所有者
            userIntegral.setIntegral(IntegralEnum.BORROWER_HOUSE.getIntegral());
            userIntegral.setContent(IntegralEnum.BORROWER_HOUSE.getMsg());//获取积分说明
            userIntegralMapper.insert(userIntegral);

        }

        userInfo.setIntegral(currentIntegral);
        //修改一下审核状态
        userInfo.setBorrowAuthStatus(borrowerApprovalVO.getStatus());

        userInfoMapper.updateById(userInfo);




    }
}
